package org.dromara.oce.service.impl;

import com.bytedance.ads.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.constraints.NotNull;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.oce.domain.base.OceBaseQo;
import org.dromara.oce.domain.qo.GetToolsMicroAppListQo;
import org.dromara.oce.domain.req.CreateToolsMicroAppReq;
import org.dromara.oce.domain.req.UpdateToolsMicroAppReq;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.stereotype.Service;
import org.dromara.oce.domain.qo.OceMicroAppQo;
import org.dromara.oce.domain.bo.OceMicroAppBo;
import org.dromara.oce.domain.vo.OceMicroAppVo;
import org.dromara.oce.domain.OceMicroApp;
import org.dromara.oce.mapper.OceMicroAppMapper;
import org.dromara.oce.service.OceMicroAppService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 字节小程序Service业务层处理
 *
 * @author dsbb
 * @date 2025-06-04
 */
@RequiredArgsConstructor
@Service
public class OceMicroAppServiceImpl extends ServiceImpl<OceMicroAppMapper,OceMicroApp> implements OceMicroAppService {

    private final OceMicroAppMapper baseMapper;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;

    /**
     * 查询字节小程序
     *
     * @param microAppId 主键
     * @return 字节小程序
     */
    @Override
    public OceMicroAppVo queryById(Long microAppId){
        return baseMapper.selectVoById(microAppId);
    }

    /**
     * 分页查询字节小程序列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 字节小程序分页列表
     */
    @Override
    public TableDataInfo<OceMicroAppVo> queryPageList(OceMicroAppQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceMicroApp> lqw = buildQueryWrapper(qo);
        Page<OceMicroAppVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的字节小程序列表
     *
     * @param qo 查询条件
     * @return 字节小程序列表
     */
    @Override
    public List<OceMicroAppVo> queryList(OceMicroAppQo qo) {
        LambdaQueryWrapper<OceMicroApp> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceMicroApp> buildQueryWrapper(OceMicroAppQo qo) {
        LambdaQueryWrapper<OceMicroApp> lqw = Wrappers.lambdaQuery();
        lqw.eq(qo.getAccountId() != null, OceMicroApp::getAccountId, qo.getAccountId());
        lqw.eq(qo.getAdvertiserId() != null, OceMicroApp::getAdvertiserId, qo.getAdvertiserId());
        lqw.eq(StringUtils.isNotBlank(qo.getAppId()), OceMicroApp::getAppId, qo.getAppId());
        lqw.like(StringUtils.isNotBlank(qo.getAppName()), OceMicroApp::getAppName, qo.getAppName());
        lqw.eq(StringUtils.isNotBlank(qo.getAuditStatus()), OceMicroApp::getAuditStatus, qo.getAuditStatus());
        return lqw;
    }

    /**
     * 新增字节小程序
     *
     * @param bo 字节小程序
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OceMicroAppBo bo) {
        OceMicroApp add = MapstructUtils.convert(bo, OceMicroApp.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;

        return flag;
    }

    /**
     * 修改字节小程序
     *
     * @param bo 字节小程序
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceMicroAppBo bo) {
        OceMicroApp update = MapstructUtils.convert(bo, OceMicroApp.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceMicroApp entity){
    }

    /**
     * 校验并批量删除字节小程序信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public boolean createToolsMicroApp(String accountId, CreateToolsMicroAppReq req) {
        ToolsMicroAppCreateV30Response response = oceanEngineThirdRemoteService.createToolsMicroApp(accountId, req);
        if (response.getCode() != 0) {
            throw new ServiceException("创建字节小程序失败," + response.getMessage());
        }
        OceMicroApp add = new OceMicroApp();
        add.setAccountId(req.getAccountId());
        add.setAdvertiserId(req.getAdvertiserId());
        add.setAppId(req.getAppId());
        add.setRemark(req.getRemark());
        String tagInfo = req.getTagInfo();
        add.setTagInfo(tagInfo);

        add.setInstanceId(response.getData().getInstanceId());
        GetToolsMicroAppListQo appListQo = new GetToolsMicroAppListQo();
        appListQo.setAccountId(req.getAccountId());
        appListQo.setAdvertiserId(req.getAdvertiserId());
        ToolsMicroAppListV30ResponseData responseList = oceanEngineThirdRemoteService.getToolsMicroAppList(appListQo);
        List<ToolsMicroAppListV30ResponseDataListInner> list = responseList.getList();
        List<ToolsMicroAppListV30ResponseDataListInner> result = list.stream().filter(obj -> obj.getInstanceId().equals( add.getInstanceId())).collect(Collectors.toList());
        if (!result.isEmpty() && result.size() > 0){
            ToolsMicroAppListV30ResponseDataListInner data = result.get(0);
            add.setAppName(data.getName());
            add.setAuditStatus(data.getAuditStatus().getValue());
            String jsonString = data.getTagInfo();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                StringBuilder stringBuilder = new StringBuilder();
                extractCategoryNames(rootNode, stringBuilder);
                add.setTagInfoDesc(stringBuilder.toString());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        boolean flag = baseMapper.insert(add) > 0;
        return flag;
    }

    @Override
    public boolean updateToolsMicroApp(String accountId, UpdateToolsMicroAppReq req) {
        ToolsMicroAppUpdateV30Response response = oceanEngineThirdRemoteService.updateToolsMicroApp(accountId, req);
        if (response.getCode() != 0) {
            throw new ServiceException("更新字节小程序失败," + response.getMessage());
        }
        OceMicroApp update = baseMapper.selectById(req.getInstanceId());
        if(update == null){
            throw new ServiceException("系统暂无此小程序");
        }
        update.setRemark(req.getRemark());

        GetToolsMicroAppListQo appListQo = new GetToolsMicroAppListQo();
        appListQo.setAccountId(req.getAccountId());
        appListQo.setAdvertiserId(req.getAdvertiserId());
        ToolsMicroAppListV30ResponseData responseList = oceanEngineThirdRemoteService.getToolsMicroAppList(appListQo);
        List<ToolsMicroAppListV30ResponseDataListInner> list = responseList.getList();
        List<ToolsMicroAppListV30ResponseDataListInner> result = list.stream().filter(obj -> obj.getInstanceId().equals( update.getInstanceId())).collect(Collectors.toList());
        if (!result.isEmpty() && result.size() > 0){
            ToolsMicroAppListV30ResponseDataListInner data = result.get(0);
            update.setAppName(data.getName());
            update.setAuditStatus(data.getAuditStatus().getValue());
            String jsonString = data.getTagInfo();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode rootNode = objectMapper.readTree(jsonString);
                StringBuilder stringBuilder = new StringBuilder();
                extractCategoryNames(rootNode, stringBuilder);
                update.setTagInfoDesc(stringBuilder.toString());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        boolean flag = baseMapper.updateById(update) > 0;
        return flag;
    }

    public static void extractCategoryNames(JsonNode node, StringBuilder result) {
        if (node.has("category_name")) {
            if (result.length() > 0) {
                result.append("-");
            }
            result.append(node.get("category_name").asText());
        }

        if (node.has("categories")) {
            JsonNode categories = node.get("categories");
            for (JsonNode category : categories) {
                extractCategoryNames(category, result);
            }
        }
    }
}
